library(vegan)
library(ggplot2)
otu <- read.delim('otu_table.txt', row.names = 1, sep = '\t', stringsAsFactors = FALSE, check.names = FALSE)
otu <- data.frame(t(otu))
env <- read.delim('env_table.txt', row.names = 1, sep = '\t', stringsAsFactors = FALSE, check.names = FALSE)
otu_cca <- cca(otu~., env)
cca_coef <- coef(otu_cca)
r2 <- RsquareAdj(otu_cca)
otu_cca_noadj <- r2$r.squared
otu_cca_adj <- r2$adj.r.squared
otu_cca_exp_adj <- otu_cca_adj * otu_cca$CCA$eig/sum(otu_cca$CCA$eig)
otu_cca_eig_adj <- otu_cca_exp_adj * otu_cca$tot.chi
otu_cca_test <- anova.cca(otu_cca, permutations = 999)
otu_cca_test_axis <- anova.cca(otu_cca, by = 'axis', permutations = 999)
otu_cca_test_axis$`Pr(>F)` <- p.adjust(otu_cca_test_axis$`Pr(>F)`, method = 'bonferroni')
vif.cca(otu_cca)
otu_cca_forward_pr <- ordiR2step(cca(otu~1, env), scope = formula(otu_cca), R2scope = TRUE, direction = 'forward', permutations = 999)
exp_adj <- RsquareAdj(otu_cca_forward_pr)$adj.r.squared * otu_cca_forward_pr$CCA$eig/sum(otu_cca_forward_pr$CCA$eig)
cca1_exp <- paste('CCA1:', round(exp_adj[1]*100, 2), '%')
cca2_exp <- paste('CCA2:', round(exp_adj[2]*100, 2), '%')
otu_cca_forward_pr.scaling1 <- summary(otu_cca_forward_pr, scaling = 1)
otu_cca_forward_pr.site <- data.frame(otu_cca_forward_pr.scaling1$sites)[1:2]
otu_cca_forward_pr.env <- data.frame(otu_cca_forward_pr.scaling1$biplot)[1:2]
otu_cca_forward_pr.env$name <- rownames(otu_cca_forward_pr.env)
map<- read.delim('group.txt', row.names = 1, sep = '\t')
otu_cca_forward_pr.site$name <- rownames(otu_cca_forward_pr.site)
otu_cca_forward_pr.site$group <- map$group
library(ggrepel)
color=c( "#3C5488B2","#00A087B2",
"#F39B7FB2","#91D1C2B2",
"#8491B4B2", "#DC0000B2",
"#7E6148B2","yellow",
"darkolivegreen1", "lightskyblue",
"darkgreen", "deeppink", "khaki2",
"firebrick", "brown1", "darkorange1",
"cyan1", "royalblue4", "darksalmon",
"darkgoldenrod1", "darkseagreen", "darkorchid")
p <- ggplot(otu_cca_forward_pr.site, aes(CCA1, CCA2)) +
geom_point(size=1,aes(color = group,shape = group)) +
stat_ellipse(aes(color = group), level = 0.95, show.legend = FALSE, linetype = 2) +
scale_color_manual(values = color[1:length(unique(map$group))]) +
theme(panel.grid.major = element_line(color = 'gray', size = 0.1), panel.background = element_rect(color = 'black', fill = 'transparent'),
legend.title = element_blank(), legend.key = element_rect(fill = 'transparent'), plot.title = element_text(hjust = 0.5)) +
labs(x = cca1_exp, y = cca2_exp) +
geom_vline(xintercept = 0, color = 'gray', size = 0.5) +
geom_hline(yintercept = 0, color = 'gray', size = 0.5) +
geom_segment(data = otu_cca_forward_pr.env, aes(x = 0, y = 0, xend = CCA1, yend = CCA2), arrow = arrow(length = unit(0.2, 'cm')), size = 0.3, color = 'blue') +
geom_text(data = otu_cca_forward_pr.env, aes(CCA1 * 1.2, CCA2 * 1.2, label = name), color = 'blue', size = 3) +
geom_label_repel(aes(label = name, color = group), size = 3, box.padding = unit(0, 'lines'), show.legend = FALSE)
p